<template>
  <div class="app-container">
    <el-button style="margin-bottom: 15px" type="success" size="mini" @click="onCreateBtnClick">添加分类</el-button>
    <el-button style="margin-bottom: 15px" type="primary" size="mini" @click="submitConfig('batchShow')">提交分类配置</el-button>
    <div class="updateNewTime">分类配置最新提交时间: {{submitTime}}</div>
    <el-table v-loading="loading" border :data="informationData" style="width: 100%">
      <el-table-column label="分类名称(资讯端展示)" prop="className" align="center"></el-table-column>
      <el-table-column label="分类编码" prop="classCode" align="center" width="100"></el-table-column>
      <el-table-column label="排序" prop="sort" align="center" width="100"></el-table-column>
      <el-table-column label="映射关系(采集咨询分类名)" prop="collexts" align="left">
        <template slot-scope="scope">
          <span style="white-space: pre">{{scope.row.mappingRelation}}</span>         
        </template>
      </el-table-column>
      <el-table-column label="对应城市" align="left">
        <template slot-scope="scope">
          <el-popover class="cityPopover" placement="top-start" trigger="hover" width="240" 
          :content="(scope.row.commonCity[0] ? scope.row.commonCity.join('、') : '') + (scope.row.commonCity[0] && scope.row.otherCity[0] ? '、' : '') + (scope.row.otherCity[0] ? scope.row.otherCity.join('、') : '')">
            <div class="cityColumn" slot="reference">
              <div class="cityDiv" v-if="scope.row.commonCity[0]">{{scope.row.commonCity.join("、")}}</div>
              <div class="cityDiv" v-if="scope.row.otherCity[0]">{{scope.row.otherCity.join("、")}}</div>
              <div class="cityTotalDiv">{{scope.row.commonCity? "共" + Number(scope.row.commonCity.length + scope.row.otherCity.length) +"城": "-"}}</div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" prop="show" align="center" width="100">
        <template slot-scope="scope">
          <template v-if="scope.row.show == true">显示</template>
          <template v-if="scope.row.show == false">隐藏</template>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createdTimes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后编辑时间" prop="updateTime" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTimes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center" prop="submit">
        <template slot-scope="scope">
          <span :class="scope.row.submit ? '' : 'active'">{{scope.row.submit | subState}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"  class="line" type="text" @click="sortInformation(scope.row)"  >更改排序</el-button>
          <el-button size="mini"  class="line" type="text" @click="editInformation(scope.row)" >编辑</el-button>
          <el-button size="mini" type="text" @click="toggleShow(scope.row, scope.$index)">
            <template v-if="scope.row.show == true">隐藏</template>
            <template v-if="scope.row.show == false">显示</template>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 更改排序的状态 -->
    <el-dialog title="更改排序" :visible.sync="dialogFormVisible" width="500px" >
      <div style="width:200px">
        <el-form :model="form">
        <el-form-item label="" :label-width="formLabelWidth">
          <el-input v-model="form.sort" placeholder="输入0-99数字" maxLength=2 @input="form.sort=form.sort.replace(/[^\d]/g,'')" ></el-input>
        </el-form-item>
      </el-form>
      </div>
      <div style="margin:20px 0 0 60px; color:red">数字越小排序越靠前</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="endter">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增-编辑弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="showEditIDialog" >
      <!-- <el-form :model="form" label-width="200px" ref="prjoForm" :rules="rules" > -->
      <el-form :model="form" label-width="120px" ref="prjoForm">
        <!-- 分类名称 -->
        <div class="title">
          <div class="input" >
            <el-form-item  prop="className">
              <label slot="label"><span style="color:red">*</span>&nbsp;&nbsp;分类名称</label>
              <el-input maxlength=4 v-model.trim="form.className" placeholder="至多4个字" autocomplete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <!-- 分类编码 -->
        <div class="title">
          <div class="input" >
            <el-form-item  prop="classCode">
              <label slot="label"><span style="color:red">*</span>&nbsp;&nbsp;分类编码</label>
              <el-input v-model.trim="form.classCode" placeholder="至多20个字符" maxlength=20 autocomplete="off"></el-input>
            </el-form-item>
         </div>
        </div>
        <!-- 一个整体 城市 -->
        <el-form-item prop="type">
          <label slot="label"><span style="color:red">*</span>&nbsp;&nbsp;对应城市</label>
          <el-checkbox-group v-model="form.type"></el-checkbox-group>
          
          <!-- 全部城市 -->
          <el-form-item>
            <el-checkbox v-model="citycheck.commAll"  @change="CheckAllChange">全选</el-checkbox>
          </el-form-item>

          <!-- 常用城市 -->
          <el-form-item >
            <div>常用城市</div>
            <el-checkbox v-model="citycheck.commCity" @change="commcity">全选</el-checkbox>
            <el-checkbox-group  class="commCity"  v-model="form.checkedCitiesComm"  @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in form.checkedAllcity[0]" :label="city" :key="city">{{city}}</el-checkbox>
            </el-checkbox-group> 
          </el-form-item>

          <!-- 其他城市 -->
          <el-form-item style="margin-top: 10px">
            <div>其他城市</div>
            <el-checkbox v-model="citycheck.otherCity" @change="handleCheckAllChangeOther" >全选</el-checkbox>
            <el-checkbox-group  class="commCity"  v-model="form.checkedCitiesOther"  @change="handleCheckedCitiesChangeOther">
              <el-checkbox v-for="city in form.checkedAllcity[1]" :label="city" :key="city">{{city}}</el-checkbox>
            </el-checkbox-group> 
          </el-form-item> 
        </el-form-item>
        <!-- 渠道和分类 -->
        <el-form-item style="margin-top: 10px">
          <label slot="label"><span style="color:red">*</span>&nbsp;&nbsp;对应采集分类</label>
          <template v-for="(item, index) in allClassification">
            <div :key="index">
              <div class="orgin">
                <el-checkbox v-model="item.checked" @change="handleCheckAllChannel(item,index)">{{item.channelName}}</el-checkbox>
              </div>
              <el-checkbox-group v-model="form.checkedClassification[index].className" @change="handleCheckedClassificationChange(item,index)">
                <el-checkbox v-for="items in item.className" :label="items" :key="items">{{items}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
        </el-form-item>
        <!-- 是否显示或隐藏 -->
        <div class="isShowState">
          <el-form-item label="" prop="isShow">
            <label slot="label"><span style="color:red">*</span>&nbsp;&nbsp;是否显示</label>
            <el-radio v-model="form.isShow" :label="true">是</el-radio>
            <el-radio v-model="form.isShow" :label="false">否</el-radio>
          </el-form-item>
        </div>
      </el-form>
      <!-- 底部保存取消 -->
      <div class="foot">
        <el-button type="primary" @click="!form.id ? addClassfy('prjoForm') : editClassfy('prjoForm')">保 存</el-button>
        <el-button @click="showEditIDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getInformationList,
  getPreviewInfoWithId,
  sortStatus,
  addClassfy,
  submitConfig,
} from "@/api/shulanAgent/informationManage";
import {VueDebounce, timeChange} from "@/utils/index"

const state = [
  { type: false, name: "未提交" },
  { type: true, name: "已提交" },
];

export default {
  name: "informationManage",
  data() {
    return {
      citycheck:{
        commAll:false, // 全部按钮
        commCity:false, // 常用城市按钮
        otherCity:false, // 其他城市
        checkSouhu:false, // 搜狐
      },
      allChannel: [], // 采集渠道的集合
      allClassification: [], // 采集渠道下分类的集合
      form: {
        checkedClassification: [], // 被选中渠道下的分类
        type:[],
        className: '',
        classCode: '', // 分类编码
        checkedAllcity:[], // 所有城市集合
        checkedCitiesComm:[], // 常用城市
        checkedCitiesOther:[], // 其他城市
        isShow:undefined,
        ids:[], // 所有id的集合
        commonCity: undefined,
        cityAllComm: [], // 常用城市被选中状态的集合
        cityAllOther: [], // 其他城市被选中状态的集合
        checkAllcity: undefined, // 所以城市集合
        sort: "",
        id:null,
        content: null,
      },
      dialogTitle: '', // 弹出框标题
      submitTime: '', // 最后更新时间
      informationData: [], // 资讯列表数据
      loading: false,
      dialogFormVisible: false, // 排序弹窗
      showEditIDialog: false, // 新增创建，编辑弹框
      formLabelWidth: "60px",
    };
  },

  created() {
    this.getInformationList();
    // 获取资讯城市字典
    this.getInformationCity();
    //获取分类
    this.getInformationClassfy();
    // 防抖
    this.addClassfy = VueDebounce(this.addClassfy, 300)
    this.editClassfy = VueDebounce(this.editClassfy, 300)
    this.sortInformation = VueDebounce(this.sortInformation, 300)
    this.endter = VueDebounce(this.endter, 300)
  },

  mounted() {},

  methods: {
    // 获取资讯列表
    getInformationList() {
      this.loading = true;
      getInformationList().then((res) => {
        if (res.code === 200) {
          let ids = []         
          res.data.forEach(v => {
            v.mappingRelation = ''
            v.stringList.forEach(item => {
              v.mappingRelation += item + '\n'
            })
          })
          this.informationData = res.data;
          this.submitTime = res.data[0] ? res.data[0].submitTime : '--'
          var arrOther = res.data.map(v=>{
          return  v.otherCity
          })
          res.data.map(v=>ids.push(v.id))
          this.form.ids = ids
          this.loading = false;
        }
      });
    },

    //获取资讯城市字典
    async getInformationCity() {
      let response = await this.getDicts("information_use_city")
      //常用城市
      let cityAllComm = [];
      response.data.map(item => {
        cityAllComm.push(item.dictLabel);
      })
      this.form.cityAllComm = cityAllComm;
      let res = await this.getDicts("information_other_city")
      // 其他城市
      let cityAllOther = [];
      res.data.map(item => {
      cityAllOther.push(item.dictLabel);
      })
      this.form.cityAllOther = cityAllOther;
      this.form.checkedAllcity.push(cityAllComm,cityAllOther)
    },
    // 获取对应采集分类
    async getInformationClassfy() {
      let that = this
      this.getDicts("information_channel").then(res => {
        if (res.code == 200) {
          that.allChannel = res.data
          res.data.forEach(item => {
            let cItem = {
              channelName: item.dictLabel,
              className: [],
            }
            let aItem = []
            this.form.checkedClassification.push(cItem);
            that.getDicts(`information_${item.dictValue}`).then(response => {
              if (response.code == 200) {
                let arrAll = [];
                response.data.forEach(val => {
                  arrAll.push(val.dictLabel)
                })
                aItem = {
                  channelName: item.dictLabel,
                  checked: false,
                  className: arrAll,
                }
                that.allClassification.push(aItem)
                that.form.checkedClassification[item.dictLabel] = []
              }
            })
          })
        }
      })
    },
    //清空列表
    handadd() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    // 切换显示隐藏列表
    toggleShow(row, index) {
     let _this = this;
      let listData = this.informationData;
      let changeItem = listData[index];
      let id = row.id;
      let tips = ''
      let show = row.show;
      if(show){
        show == true
        tips = '确定要隐藏该资讯吗？'
      }else{
          show ==false;
          tips = '确定要显示该资讯吗？'
      }
       let params = {
        show: !show,
        id: id,
      };
      this.showConfirmDialog(tips,function(){
        getPreviewInfoWithId(params).then((res) => {
          if (res.code == 200) {
            _this.getInformationList();
          }
        });
      })
    },
    //确认提示框
    showConfirmDialog(hint, callback) {
      this.$confirm(hint, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        callback();
      })
    },
    //更改排序
    sortInformation(e) {
      this.dialogFormVisible = true;
      this.form.sort = e.sort;
      this.form.id= e.id
    },
    //更改状态---确定按钮
    endter() {
      if(this.form.sort === '') {
        this.$message('排序数值不可为空')
        return
      }
      let params = {
        sort: this.form.sort,
        id: this.form.id,
      };
      sortStatus(params).then((res) => {
         this.dialogFormVisible = false;
            this.$message({
            type:'success',
            message:'更改成功!'
          });
        if (res.code == 200) {
          this.getInformationList();
        }
      });
    },
    //新建分类列表
    onCreateBtnClick() {
      this.dialogTitle = '添加分类'
      // 置空表单
      this.form.id = ''
      this.form.className = undefined
      this.form.checkedCitiesComm = []
      this.form.checkedCitiesOther = []
      this.form.isShow = undefined
      // 数组顺序变为一致
      let arr = []
      this.allClassification.forEach(item => {
        arr.push({
          channelName: item.channelName,
          className: []
        })
      })
      this.form.checkedClassification = arr
      // 判断全选
      this.handleCheckedCitiesChange(this.form.checkedCitiesComm)
      this.handleCheckedCitiesChangeOther(this.form.checkedCitiesOther)
      this.allClassification.forEach((v,i) => {
        this.handleCheckedClassificationChange(v,i)
      })
      // 弹出对话框
      this.showEditIDialog = true;
    },
    // 全部城市---全选按钮
    CheckAllChange(v){
      this.form.checkedCitiesComm = v ? this.form.checkedAllcity[0] : []
      this.citycheck.commCity = v ? true : false
      this.form.checkedCitiesOther =v ? this.form.checkedAllcity[1] : []
      this.citycheck.otherCity=v ? true : false
      this.citycheck.commAll = v ? true : false
    },
    // 常用城市---全选按钮
    commcity(val) {
      this.form.checkedCitiesComm = val ? this.form.checkedAllcity[0] : [];
      this.citycheck.commAll = this.citycheck.otherCity && this.citycheck.commCity ? true : false
    },
    // 常用城市---单选
    handleCheckedCitiesChange(value) {
      let commCity = value.length;
      this.citycheck.commCity = commCity === this.form.checkedAllcity[0].length
      this.citycheck.commAll= this.citycheck.commCity && this.citycheck.otherCity ? true : false//顶部所有城市全选按钮控制
    },
    // 其他城市---全选
    handleCheckAllChangeOther(val){
      this.form.checkedCitiesOther = val ? this.form.checkedAllcity[1] : [];
      this.citycheck.commAll = this.citycheck.otherCity && this.citycheck.commCity ? true : false
    },
     // 其他城市---单选
    handleCheckedCitiesChangeOther(value) {
      let otherCity = value.length;
      this.citycheck.otherCity = otherCity === this.form.checkedAllcity[1].length
      this.citycheck.commAll = this.citycheck.commCity && this.citycheck.otherCity ? true : false//顶部所有城市全选按钮控制
    },
    // 分类全选按钮
    handleCheckAllChannel(val,index){
      this.form.checkedClassification[index].className = val.checked ? this.allClassification[index].className : [];
      this.allClassification[index].checked != this.allClassification[index].checked;
    },
    // 分类单选按钮
    handleCheckedClassificationChange(val, index){
      let valLength = val.className.length;
      this.allClassification[index].checked = valLength === this.form.checkedClassification[index].className.length;
    },
    // 新增分类列表数据--确定--弹框按钮
    addClassfy(prjoForm,typeId){
      let count = 0
      this.form.checkedClassification.forEach(v => {
        count += v.className.length
      })
      if(this.form.checkedCitiesComm.length == 0 && this.form.checkedCitiesOther.length == 0){
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(!this.form.className){
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(!this.form.classCode) {
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(this.form.isShow === undefined){
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(!count) {
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else{
        let params = {
          className:this.form.className,
          classCode:this.form.classCode,
          commonCity:this.form.checkedCitiesComm,
          otherCity:this.form.checkedCitiesOther,
          collexts:this.form.checkedClassification,
          show:this.form.isShow,
        }
        addClassfy(params).then(res=>{
          this.showEditIDialog = false
            this.getInformationList()
        })
      }
    },
    //编辑确定--弹框按钮
    editClassfy(prjoForm){
      let count = 0
      this.form.checkedClassification.forEach(v => {
        count += v.className.length
      })
      if(this.form.checkedCitiesComm.length == 0 && this.form.checkedCitiesOther.length == 0){
        this.$alert('保存失败，请填写所以带*号内容再试', {
        confirmButtonText: '确定',
        callback: action => {}
        });
      }else if(!this.form.className){
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(!this.form.classCode) {
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(this.form.isShow === undefined){
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else if(!count) {
        this.$alert('保存失败，请填写所以带*号内容再试', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }else{
        let params = {
          className:this.form.className,
          classCode:this.form.classCode,
          commonCity:this.form.checkedCitiesComm,
          otherCity:this.form.checkedCitiesOther,
          collexts:this.form.checkedClassification,
          show:this.form.isShow,
          id:this.form.id
        }
        addClassfy(params).then(res=>{
          this.showEditIDialog = false
          this.getInformationList()
        })
      }
    },
    //编辑
    editInformation(e){
      this.dialogTitle = '编辑分类'
      this.form.id = e.id
      this.form.className = e.className
      this.form.isShow = e.show
      this.form.checkedCitiesComm = e.commonCity
      this.form.checkedCitiesOther = e.otherCity
      this.form.classCode = e.classCode

      let arr = []
      this.allClassification.forEach(item => {
        arr.push({
          channelName: item.channelName,
          className: []
        })
      })
      this.form.checkedClassification = arr

      // 就这一段很关键 不要乱碰!!!
      if(e.collexts[0]) {
        this.form.checkedClassification.forEach(val => {
          e.collexts.forEach(v => {
            if(val.channelName === v.channelName) {
              val.className = v.className
            }
          })
        })
      }
      
      this.handleCheckedCitiesChange(this.form.checkedCitiesComm)
      this.handleCheckedCitiesChangeOther(this.form.checkedCitiesOther)
      this.allClassification.forEach((v,i) => {
        this.handleCheckedClassificationChange(v,i)
      })
      this.showEditIDialog = true;
    },
    //提交分类
    submitConfig(){
      let params = {
        ids:this.form.ids
      }
      submitConfig(params).then(res=>{
        if(res.code == 200) {
          this.$message.success(res.msg)
          this.getInformationList()
        }else {
          this.$message(res.msg)
        } 
      })
    }
  },
  filters: {
    subState(type) {
      const substate = state.find((obj) => {
        return obj.type === type;
      });
      return substate ? substate.name : null;
    },
  },
};
</script>

<style lang="scss" scoped>
.updateNewTime {
  margin-bottom: 10px;
  padding-left: 2px;
  font-size: 14px;
  font-weight: 700;
}
.title{
  display: flex;
  margin-bottom: 15px;
}
.el-form-item {
    margin-bottom: 0; 
}
.active {
  color: red;
}

.nameCity{
margin: 10px 0 5px 50px;
}
.commCity{
  display: flex;
  flex-wrap: wrap;
}
.name{
  width: 150px;
  text-align: right;
}
.city-origin{
  display: flex;
  margin: 15px 0;
  align-content: center;
}

.foot{
  display: flex;
  justify-content: flex-start;
  margin-top: 20px;
  padding-left: 120px;
}
.cityColumn {
  display: flex;
  align-items: center;
  color: rgba(65, 145, 250, 1);
  .cityDiv {
    flex: 1;
    display: -webkit-box;
    overflow: hidden; /*超出宽度部分隐藏*/
    text-overflow: ellipsis; /*超出部分以点号代替*/
    -webkit-line-clamp: 1; /*行数*/
    -webkit-box-orient: vertical;
  }
}

.line{
  // border: 1px solid black;
  position: relative;
}
.line::after{
  content: '';
  position: absolute;
  right: -8px;
  bottom: 8px;
  height: 10px;
  border: 1px solid #bbb9b9;
}
</style>

